import {
    Inject, Controller, Post, Get,
    Body, Query
} from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { OrderService } from '../service/order.service';
import { Order } from '../entity/order.entity';

@Controller('/order')
export class OrderController {
    @Inject()
    ctx: Context;

    @Inject()
    orderService: OrderService;

    @Post('/create')
    async create(@Body() order: Partial<Order>) {
        try {
            const result = await this.orderService.create(order);
            return {
                code: 200,
                message: '创建成功',
                data: result
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '创建失败'
            };
        }
    }

    @Post('/update')
    async update(@Body() order: Partial<Order>) {
        try {
            const success = await this.orderService.update(order.id, order);
            return {
                code: 200,
                message: success ? '更新成功' : '更新失败'
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '更新失败'
            };
        }
    }

    @Get('/del')
    async delete(@Query('id') id: number,) {
        try {
            const success = await this.orderService.delete(id);
            return {
                code: 200,
                message: success ? '删除成功' : '删除失败'
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '删除失败'
            };
        }
    }

    @Get('/detail')
    async getInfo(@Query('id') id: number) {
        try {
            const order = await this.orderService.getInfo(id);
            return {
                code: 200,
                message: '获取成功',
                data: order
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '获取失败'
            };
        }
    }

    @Get('/list')
    async getList(
        @Query('page') page: number,
        @Query('pageSize') pageSize: number,
        @Query('orderNo') orderNo?: string,
        @Query('userId') userId?: number,
        @Query('status') status?: number
    ) {
        try {
            const [list, total] = await this.orderService.getList({
                page,
                pageSize,
                orderNo,
                userId,
                status
            });

            return {
                code: 200,
                message: '获取成功',
                data: list,
                total
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '获取失败'
            };
        }
    }
}